var imkbizle = function() {

	//private area
	var source = isnet; //TODO: allow user to select source site.

	var setLabel = function(stock, button) {
		button.label = stock.Name + ": " + stock.Latest;
	};

	var setArrow = function(stock, button) {
		button.image = "chrome://imkbizle/skin/arrow_"
			+ ((stock.Latest >= stock.Open) ? "up" : "down") + ".gif";
	};

	var setToolTipText = function(stock, button) {
		var tiptext = "";
		var stats = $H(stock);
		//exclude info that won't be shown on tooltip
		stats.unset("Name");
		stats.each(function(stat) {
			if (stat.value) {
				tiptext += source.locale.getString("stock." + stat.key) + ": " + stat.value + " | ";
			}
		});
		button.tooltipText = tiptext.replace(/(.*) \| $/, "$1"); //strip last seperator
	};

	var infoReceived = function(transport) {
		var stock = source.getStock(transport.responseText);
		var target_button = this; //see bind method of prototype library.
		setLabel(stock, target_button);
		setArrow(stock, target_button);
		setToolTipText(stock, target_button);
	};

	var resetButton = function(button) {
		button.label = source.locale.getString("status.loading");
		button.image = "";
		button.tooltipText = source.locale.getString("status.wait");
	};

	var addMenuItem = function(menu, label, click_callback) {
		var item = document.createElement("menuitem");
		item.setAttribute("label", label);
		if (click_callback) {
			item.setAttribute("onclick", click_callback);
		}
		menu.appendChild(item);
	};

	var fillStockList = function() {
		var stocks = prefs.getStocks();
		stocks.each(function(stock) {
			addMenuItem($('stock-menu'), stock);
		});
		return stocks;
	};

	// public area
	return {

		refresh_enabled: true,

		// Install a timeout handler to install the interval routine
		startup: function() {
			var stocks = fillStockList();
			// check if any saved value exists for default stock to be
			// shown at startup, if none show first stock.
			var index = prefs.getIntPref(prefs.settings.default_stock.target, 0);
			source.locale = $("string-bundle");
			$("stock-button0").setAttribute("stockname", stocks[index]);
			imkbizle.refreshInformation();
			var refresh_interval = prefs.getIntPref(prefs.settings.refresh_interval.target, 2) + 1;
			window.setInterval("imkbizle.refreshInformation()", refresh_interval*60*1000); //default 3 min.
		},

		// Called periodically to refresh the stock information
		refreshInformation: function(target_button) {
			if (imkbizle.refresh_enabled) {
				var query = "button[@class=stock-button]";
				query += target_button ? "[@stockname=" + target_button.getAttribute("stockname") + "]" : "";
				jQuery(query).each(function() {
					var target = this;
					var stockname = target.getAttribute("stockname");
					resetButton(target);
					var request = new Ajax.Request(source.url, {
						method: 'get',
						parameters: source.createParams(stockname),
						onSuccess: bind(target, infoReceived),
						onFailure: function(){ throw("couldn't retrieve data from '" + source.url + "'") }
					});
					target.setAttribute("url", request.url);
				});
			}
		},

		onSelectStock: function(event) {
			var target_button = event.target.parentNode.parentNode;
			target_button.setAttribute("stockname", event.target.label);
			imkbizle.refreshInformation(target_button);
		},

		showSourcePage: function(event) {
			var load_location = prefs.settings.load_location;
			var current_button = $(event.target.getAttribute("buttonid"));
			var url = current_button.getAttribute("url");
			var target = prefs.getIntPref(load_location.target);
			if (target == prefs.NEW_WINDOW) {
				window.open(url);
			} else if ((target == prefs.NEW_TAB) || (target == prefs.UNFOCUSED_TAB)) {
				var myTab = getBrowser().addTab(url, null, null);
				if(target == prefs.NEW_TAB)
					getBrowser().selectedTab = myTab;
			} else {
				getBrowser().loadURI(url);
			}
		},

		toggleRefresh: function(event) {
			imkbizle.refresh_enabled = !imkbizle.refresh_enabled;
			var label_key = imkbizle.refresh_enabled
				? "label.disable_refresh"
				: "label.enable_refresh";
			event.target.label = source.locale.getString(label_key);
		},

		openPreferences: function(event) {
			window.openDialog("chrome://imkbizle/content/prefs.xul",
					"_blank", "centerscreen, chrome,resizable=no,dependent=yes")
		},

		addStockButton: function(event) {
			var first_id = jQuery("div:first")[0].id;
			var first_id_num = parseInt(first_id.replace(/stock-div(\d+)/, "$1"));
			var new_id_num = first_id_num + 1;
			var new_id = "stock-div" + new_id_num;
			var first_div = $(first_id);
			var new_div = first_div.cloneNode(true);
			var rightclick_menu = new_div.firstChild;
			var show_source_menu = rightclick_menu.firstChild;
			var button = rightclick_menu.nextSibling;
			var menupopup = button.firstChild;
			var remove_callback = "imkbizle.removeStockButton('" + new_id + "')";
			new_div.id = new_id;
			rightclick_menu.id = "rightclick_menu" + new_id_num;
			if (first_id == "stock-div0") {
				// remove disable-enable refresh menu item from non-initial stock buttons.
				var item  = rightclick_menu.firstChild.nextSibling;
				item.parentNode.removeChild(item);
				addMenuItem(rightclick_menu, source.locale.getString("label.remove"), remove_callback);
			} else {
				rightclick_menu.lastChild.setAttribute("onclick", remove_callback);
			}
			button.id = "stock-button" + new_id_num;
			show_source_menu.setAttribute("buttonid", button.id);
			button.setAttribute("context", "rightclick_menu" + new_id_num);
			menupopup.id = "stock-menu" + new_id_num;
			event.target.parentNode.insertBefore(new_div, first_div);
		},

		removeStockButton: function(button_id) {
			button = $(button_id);
			button.parentNode.removeChild(button);
		}
	}
}()

// Install load handler
window.addEventListener("load", function(e) { imkbizle.startup(); }, false);
